package com.exmaple.lemlin.app;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;

import com.exmaple.lemlin.entity.DaoMaster;
import com.exmaple.lemlin.entity.DaoSession;
import com.exmaple.lemlin.server.NotificationCollectorService;
import com.exmaple.lemlin.server.XMPPService;
import com.exmaple.lemlin.xmpp.XmppConnection;

import org.jxmpp.jid.EntityFullJid;

public class APPIM extends Application {

    private static Context mContext;
    private static EntityFullJid loginUser;
    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();

        toggleNotificationListenerService(mContext);

        this.startService(new Intent(mContext, XMPPService.class));

        this.setDatabase();
    }

    public static Context getContext() {
        return mContext;
    }

    public static EntityFullJid getLoginUser() {
        return loginUser;
    }

    public static void setLoginUser(EntityFullJid loginUser) {
        APPIM.loginUser = loginUser;
    }

    public static void setContext(Context mContext) {
        APPIM.mContext = mContext;
    }


    private void setDatabase() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper((this), ("im.db"), (null));
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }

    private void toggleNotificationListenerService(Context context) {
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(context, NotificationCollectorService.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(new ComponentName(context, NotificationCollectorService.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }
}
